<template>
  <view class="">
    <NavBar :title="title" :autoBack="false" id="nav">
      <template #left>
        <view class="navbar-left center" @click="goBack">
          <u-icon name="arrow-left" color="#007aff" size="34"></u-icon>
        </view>
      </template>
    </NavBar>
    <view class="block"></view>
    <view class="navbox">
      <u-subsection
        :list="tabsList"
        bg-color="#fff"
        button-color="#fff"
        v-model="activeIndex"
        @change="changeNav"
      ></u-subsection>
    </view>
    <view class="content">
      <view class="components">
        <DraggableList @setCurTarget="setCurTarget"></DraggableList>
        <FragmentList ref="fragmentList" @setModleTarget="setModleTarget"></FragmentList>
      </view>
      <view class="drop-container">
        <view
          v-for="(item, index) in showData"
          :key="index"
          @dragover.prevent
          @drop="onDrop(index)"
        >
          <view class="questions">
            <EachQuestion
              :question="item"
              @deleteModule="deleteModule(index)"
              @addFragment="addFragment(index)"
            >
            </EachQuestion>
          </view>
        </view>
        <view class="add—module" @click="addmodules"> + 添加模塊 </view>
      </view>
    </view>
    <view class="footer">
      <view class="btn" v-if="+activeIndex !== 0" @click.stop="toPre">
        上一步
      </view>
      <view class="btn" v-if="+activeIndex !== 2" @click.stop="toNext">
        下一步
      </view>
      <view class="btn" v-if="activeIndex === 2" @click.stop="submit">
        提交
      </view>
    </view>
    <u-popup
      v-model="showPopup"
      border-radius="14"
      mode="center"
      width="1000rpx"
      height="500rpx"
    >
      <view class="popup-content">
        <view class="popup-tips"> 設置檢測表名稱 </view>
        <view class="content-view">
          <uni-forms ref="baseForm" :modelValue="baseFormData" :rules="rules">
            <uni-forms-item label="名稱" name="form_template_name" required>
              <uni-easyinput
                v-model="baseFormData.form_template_name"
                placeholder="請輸入檢查表名稱"
              />
            </uni-forms-item>
            <uni-forms-item label="備註" name="form_template_remark" required>
              <uni-easyinput
                v-model="baseFormData.form_template_remark"
                placeholder="請輸入檢查表備註"
              />
            </uni-forms-item>
          </uni-forms>
        </view>
        <view class="popup-btns">
          <view class="btn" @click="showPopup = false"> 取消 </view>
          <view class="btn" @click="onAddConfirm"> 確定 </view>
        </view>
      </view>
    </u-popup>
    <uni-popup ref="message" type="message">
      <uni-popup-message
        type="warn"
        :message="messageText"
        :duration="3000"
      ></uni-popup-message>
    </uni-popup>
    <u-popup
      v-model="showAddFragment"
      border-radius="14"
      mode="center"
      width="1000rpx"
      height="500rpx"
    >
      <view class="popup-content">
        <view class="popup-tips"> 設置模塊名稱 </view>
        <view class="content-view1">
          <uni-forms
            ref="fragmentForm"
            :modelValue="fragmentData"
            :rules="fragmentDataRules"
          >
            <uni-forms-item
              label="名稱"
              name="form_template_module_name"
              required
            >
              <uni-easyinput
                v-model="fragmentData.form_template_module_name"
                placeholder="請輸入模塊名稱"
              />
            </uni-forms-item>
          </uni-forms>
        </view>
        <view class="popup-btns">
          <view class="btn" @click="showAddFragment = false"> 取消 </view>
          <view class="btn" @click="onAddFragment"> 確定 </view>
        </view>
      </view>
    </u-popup>
  </view>
</template>

<script>
import NavBar from '@/component/NavBar'
import DraggableList from './components/DraggableList.vue'
import FragmentList from './components/FragmentList.vue'
import EachQuestion from './components/EachQuestion.vue'
import {
  addTemplate,
  getTemplateDetail,
  editTemplate,
  getFormTemplateDetail,
  getDetailFormTemplateDetail,
  addModule,
} from '@/api/template.js'
export default {
  name: 'addForms',
  components: {
    NavBar,
    DraggableList,
    EachQuestion,
    FragmentList,
  },
  data() {
    return {
      title: '設置檢查表',
      tabsList: [
        {
          name: '前置工作',
          ident: 0,
          tabName: 'frontendData',
        },
        {
          name: '工作檢核',
          ident: 1,
          tabName: 'reviewData',
        },
        {
          name: '接績',
          ident: 2,
          tabName: 'achievementsData',
        },
      ],
      target: null,
      activeIndex: 0,
      frontendData: [],
      reviewData: [],
      achievementsData: [],
      tabName: 'frontendData',
      caseId: '',
      baseFormData: {
        form_template_name: '',
        form_template_remark: '',
      },
      showPopup: false,
      rules: {
        // 对name字段进行必填验证
        form_template_name: {
          // name 字段的校验规则
          rules: [
            // 校验 name 不能为空
            {
              required: true,
              errorMessage: '請輸入檢查表單名稱',
            },
          ],
          validateTrigger: 'submit',
        },
        form_template_remark: {
          // name 字段的校验规则
          rules: [
            // 校验 name 不能为空
            {
              required: true,
              errorMessage: '請輸入檢查表單備註',
            },
          ],
          validateTrigger: 'submit',
        },
      },
      messageText: '',
      casezy_id: '',
      isEdit: false,
      id: '',
      form_template_id: '',
      isCopy: false,
      form_template_module_content: '[]',
      showAddModel: false,
      fragmentData: {
        form_template_module_name: '',
        form_template_module_content: '[]',
      },
      fragmentDataRules: {
        form_template_module_name: {
          rules: [
            {
              required: true,
              errorMessage: '請輸入模塊名稱',
            },
          ],
          validateTrigger: 'submit',
        },
      },
      curFragment: null,
      showAddFragment: false,
    }
  },
  computed: {
    showData() {
      return this[this.tabName]
    },
  },
  onLoad() {
    if (!uni.getStorageSync('islogin')) {
      this.$Toast('請先登錄')
      setTimeout(() => {
        this.toPage('Home')
      }, 1200)
    } else {
      const { casezy_form_template_id, casezy_id, isEdit, isCopy } =
        this.$Route.query
      this.casezy_form_template_id = casezy_form_template_id
      this.casezy_id = casezy_id
      this.isEdit = !!isEdit
      this.isCopy = !!isCopy
      if (this.isCopy) {
        this.onCopyGetTemDetail()
      } else if (this.isEdit) {
        this.getTemDetail()
      } else if(casezy_form_template_id) {
        this.getDetail()
      }
    }
  },
  // getTemplateDetail
  methods: {
    toPage(name) {
      this.$navi({
        route: {
          name,
        },
      })
    },
    goBack() {
      uni.navigateBack(-1)
    },
    setActive(val, tabName) {
      this.tabName = tabName
      this.activeIndex = val
    },
    setCurTarget(target) {
      this.target = target
    },
    setModleTarget(curModel) {
      this.curModel = curModel
      this.target = {
        type: 'model',
      }
      this.form_template_module_content = curModel.form_template_module_content
    },
    onDrop(index) {
      let type = this.target.type
      switch (type) {
        case 'radio':
          this[this.tabName][index].dataList.push({
            type: 'radio',
            title: '',
            options: [],
            exampleFileList: [],
          })
          break
        case 'select':
          this[this.tabName][index].dataList.push({
            type: 'select',
            title: '',
            options: [],
            exampleFileList: [],
          })
          break
        case 'input':
          this[this.tabName][index].dataList.push({
            type: 'input',
            title: '',
            options: [],
            exampleFileList: [],
          })
          break
        case 'upload':
          this[this.tabName][index].dataList.push({
            type: 'upload',
            title: '',
            options: [],
            fileList: [],
            exampleFileList: [],
          })
          break
        case 'date':
          this[this.tabName][index].dataList.push({
            type: 'date',
            title: '',
            options: [],
            exampleFileList: [],
          })
          break
        case 'time':
          this[this.tabName][index].dataList.push({
            type: 'time',
            title: '',
            options: [],
            exampleFileList: [],
          })
          break
        case 'model':
          let list = JSON.parse(this.form_template_module_content)
          this[this.tabName][index].dataList.push(...list)
          break
      }
    },
    deleteModule(index, moduleName) {
      this[this.tabName].splice(index, 1)
    },
    addFragment(index) {
      this.showAddFragment = true
      //點擊保存為模塊庫觸發出來的事件
      this.curFragment = this[this.tabName][index]
    },
    addmodules() {
      this[this.tabName].push({
        moduleName: '',
        dataList: [],
      })
    },
    changeNav(index) {
      this.tabName = this.tabsList[index].tabName
    },
    toNext() {
      switch (this.tabName) {
        case 'frontendData':
          this.tabName = 'reviewData'
          break
        case 'reviewData':
          this.tabName = 'achievementsData'
          break
      }
      this.$goTop()
      this.activeIndex++
    },
    toPre() {
      switch (this.tabName) {
        case 'reviewData':
          this.tabName = 'frontendData'
          break
        case 'achievementsData':
          this.tabName = 'reviewData'
          break
      }
      this.$goTop()
      this.activeIndex--
    },
    getDetail() {
      let data = {
        casezy_form_template_id: this.casezy_form_template_id,
        uid: uni.getStorageSync('uid'),
      }
      getFormTemplateDetail(data)
        .then((res) => {
          let resData = res.form_template
          try {
            this.baseFormData.form_template_name = resData.form_template_name
            this.baseFormData.form_template_remark =
              resData.form_template_remark
            let obj = JSON.parse(resData.form_template_content)
            this.frontendData = obj.frontendData
            this.form_template_id = resData.id
            this.achievementsData = obj.achievementsData
            this.reviewData = obj.reviewData
          } catch (err) {
            console.log(err)
          }
        })
        .catch((err) => {
          if (err.code === 102) {
            this.$ClearLogin(err.msg)
          } else {
            this.$Toast(err.msg)
          }
        })
    },
    onCopyGetTemDetail() {
      getDetailFormTemplateDetail({
        uid: uni.getStorageSync('uid'),
        id: this.casezy_form_template_id,
      }).then((resData) => {
        try {
          let obj = JSON.parse(resData.form_template_content)
          this.frontendData = obj.frontendData
          this.achievementsData = obj.achievementsData
          this.reviewData = obj.reviewData
        } catch (err) {
          console.log(err)
        }
      })
    },
    getTemDetail() {
      getDetailFormTemplateDetail({
        uid: uni.getStorageSync('uid'),
        id: this.casezy_form_template_id,
      }).then((resData) => {
        try {
          this.baseFormData.form_template_name = resData.form_template_name
          this.baseFormData.form_template_remark = resData.form_template_remark
          let obj = JSON.parse(resData.form_template_content)
          this.frontendData = obj.frontendData
          this.form_template_id = resData.id
          this.achievementsData = obj.achievementsData
          this.reviewData = obj.reviewData
        } catch (err) {
          console.log(err)
        }
      })
    },
    submit() {
      this.showPopup = true
    },
    validateInput(data, tableName) {
      let flag = true
      if (!data || !data.length) {
        this.messageText = `${tableName}未添加模塊`
        this.$refs.message.open()
        flag = false
      }
      for (let i = 0; i < data.length; i++) {
        if (!data[i].moduleName) {
          this.messageText = `請輸入${tableName}模塊${i + 1}的名稱`
          this.$refs.message.open()
          flag = false
          break
        }
        if (!data[i].dataList || !data[i].dataList.length) {
          this.messageText = `${tableName}模塊${i + 1}的未添加題目`
          this.$refs.message.open()
          flag = false
          break
        } else {
          let flagJ = true
          for (let j = 0; j < data[i].dataList.length; j++) {
            let curJ = data[i].dataList[j]
            if (!curJ.title) {
              this.messageText = `${tableName}模塊${i + 1}的第${
                j + 1
              }題未設置題目描述`
              this.$refs.message.open()
              flag = false
              break
            }
            if (
              (!curJ.options || !curJ.options.length) &&
              curJ.type !== 'upload' &&
              curJ.type !== 'date' &&
              curJ.type !== 'time' &&
              curJ.type !== 'input'
            ) {
              this.messageText = `${tableName}模塊${i + 1}的第${
                j + 1
              }題未設置選項`
              this.$refs.message.open()
              flag = false
              break
            }
          }
          if (!flagJ) {
            return
          }
        }
      }
      return flag
    },
    onAddConfirm() {
      this.$refs.baseForm.validate().then((res) => {
        if (res) {
          let obj = {
            frontendData: this.frontendData,
            reviewData: this.reviewData,
            achievementsData: this.achievementsData,
          }
          let data = {
            casezy_id: this.casezy_id,
            uid: uni.getStorageSync('uid'),
            form_template_name: this.baseFormData.form_template_name,
            form_template_remark: this.baseFormData.form_template_remark,
            form_template_content: JSON.stringify(obj),
          }
          if (!this.casezy_form_template_id || this.isCopy) {
            //  没有casezy_form_template_id 就是新增的情况 copy也走新增逻辑
            addTemplate(data)
              .then((res) => {
                this.$Toast('操作成功')
                setTimeout(() => {
                  this.showPopup = false
                  this.goBack()
                }, 300)
              })
              .catch((err) => {
                if (err.code === 102) {
                  this.$ClearLogin(err.msg)
                } else {
                  this.$Toast(err.msg)
                }
              })
          } else {
            data.id = this.form_template_id
            editTemplate(data)
              .then((res) => {
                this.$Toast('編輯成功')
                setTimeout(() => {
                  this.showPopup = false
                  this.goBack()
                }, 300)
              })
              .catch((err) => {
                if (err.code === 102) {
                  this.$ClearLogin(err.msg)
                } else {
                  this.$Toast(err.msg)
                }
              })
          }
        }
      })
    },
    onAddFragment() {
      this.$refs.fragmentForm.validate().then((res) => {
        if (res) {
          let data = {
            uid: uni.getStorageSync('uid'),
            casezy_id: this.casezy_id,
            form_template_module_name:
              this.fragmentData.form_template_module_name,
            form_template_module_content: JSON.stringify(
              this.curFragment.dataList
            ),
          }
          addModule(data)
            .then((res) => {
              this.$Toast('操作成功')
              this.$nextTick(() => {
                this.showAddFragment = false
                this.fragmentData.form_template_module_name = ''
                this.$refs.fragmentList.getModuleList()
              })
            })
            .catch((err) => {
              if (err.code === 102) {
                this.$ClearLogin(err.msg)
              } else {
                this.$Toast(err.msg)
              }
            })
        }
      })
    },
  },
}
</script>

<style lang="scss" scoped>
.block {
  height: 100rpx;
}

.tabs {
  display: flex;
  justify-content: space-around;

  .tab {
    width: 360rpx;
    height: 64rpx;
    line-height: 64rpx;
    font-weight: 400;
    color: #333333;
    margin-bottom: 16rpx;
    text-align: center;
    cursor: pointer;
  }

  .active {
    background: #ffffff;
    box-shadow: 0rpx 2rpx 2rpx 1rpx rgba(197, 197, 197, 0.25);
    border-radius: 0rpx 0rpx 0rpx 0rpx;
  }
}

.content {
  display: flex;
  justify-content: space-between;

  .movable-area {
    width: 300rpx;
    height: 300rpx;
    border: 1rpx solid red;
  }

  .components {
    position: fixed;
    top: 180rpx;
    left: 0;
    width: 700rpx;
    background: #f6f6f6;
    border-radius: 0rpx 0rpx 0rpx 0rpx;
  }

  .drop-container {
    margin-left: 740rpx;
    outline: 1rpx solid #f6f6f6;
    padding: 24rpx;
    width: 100%;

    .add—module {
      background: #e6eeff;
      border-radius: 4px 4px 4px 4px;
      border: 1px solid #e7e7e7;
      color: #3a78fc;
      padding: 12rpx;
    }
  }

  .questions {
    margin-bottom: 24rpx;
  }
}

.navbox {
  width: 70vw;
  margin: 0 auto;

  /deep/ .u-item {
    position: relative;

    &::after {
      content: '';
      width: 2rpx;
      height: 32rpx;
      background-color: #f1f1f1;
      position: absolute;
      right: 0rpx;
    }

    &.u-item-3::after {
      display: none;
    }
  }

  /deep/ .u-item-bg {
    box-shadow: 0rpx 4rpx 4rpx rgba(0, 0, 0, 0.1);
  }
}

.footer {
  display: flex;
  justify-content: flex-end;
  padding: 0 24rpx;
  gap: 24rpx;
  margin-top: 24rpx;

  .btn {
    color: #fff;
    cursor: pointer;
    background: #3a78fc;
    border-radius: 6px;
    padding: 12rpx 24rpx;
  }
}

.popup-content {
  padding-top: 24rpx;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  align-items: center;

  .popup-tips {
    font-size: 36rpx;
  }

  .content-view {
    padding: 60rpx 48rpx 40rpx;
    box-sizing: border-box;
    width: 100%;
  }
  .content-view1{
    padding: 60rpx 48rpx 154rpx;
    box-sizing: border-box;
    width: 100%;
  }
  .popup-btns {
    display: flex;
    width: 100%;
    border-top: 1px solid #ebedf0;

    .btn {
      width: 50%;
      text-align: center;
      line-height: 88rpx;
      cursor: pointer;

      &:first-child {
        border-right: 1px solid #ebedf0;
        color: #323233;
      }

      &:last-child {
        color: red;
      }
    }
  }
}

::v-deep .fixforpc-z-index {
  z-index: 99999;
}
</style>
